package com.example.easybuy.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.example.easybuy.pojo.Phone;
import com.example.easybuy.pojo.ResponseMessage;
import com.example.easybuy.util.AlipayUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class AlipayPaymentServiceImpl implements AlipayPaymentService{

    private Logger logger=Logger.getLogger(getClass());

    @Autowired
    private PhoneService phoneService;

    @Value("${alipay.appId}")
    private String appId;
    @Value("${alipay.appPrivateId}")
    private String appPrivateId;
    @Value("${alipay.appPublicId}")
    private String appPublicId;
    @Value("${alipay.getway}")
    private String getWay;


    /*
    拉起支付宝支付
     */
    @Override
    public ResponseMessage alipayPayment(String subject,String amount) {
        logger.debug("AlipayPaymentServiceImpl-alipayPayment...start...subject:"+subject+",amount:"+amount);
        float total_amount=Float.parseFloat(amount);

        ResponseMessage msg = new ResponseMessage();
        String success=null;
        try {
            //        实例化客户端
            AlipayClient alipayClient= AlipayUtil.getSign(getWay,appId,appPrivateId,appPublicId);
            //实例化具体API对应的request类，类名和接口名对应
            AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
            //调用的接口版本固定为1.0
            request.setApiVersion("1.0");
            //支付宝服务器主动通知商户服务器里指定的页面http/https路径。
            request.setNotifyUrl("http://xns9h8.natappfree.cc/AlipaySuccess");
            request.setReturnUrl("http://192.168.0.48/");
            Map map=new HashMap();
            //商户订单号
            map.put("out_trade_no", UUID.randomUUID().toString());
            //交易金额
            map.put("total_amount",total_amount);
            //交易标题
            map.put("subject",subject);
            //产品码：product_code，固定值：FAST_INSTANT_TRADE_PAY
            map.put("product_code","FAST_INSTANT_TRADE_PAY");
            String reqJsonStr= JSONObject.toJSONString(map);
            request.setBizContent(reqJsonStr);
            logger.debug("AlipayPaymentServiceImpl-alipayPayment-reqJsonStr："+reqJsonStr);
            AlipayTradePagePayResponse response=alipayClient.pageExecute(request);
            logger.debug("AlipayPaymentServiceImpl-alipayPayment-response："+response);

            if(response.isSuccess()){
                logger.info("AlipayPaymentServiceImpl-alipayPayment body："+response.getBody());
                msg.setCode("200");
                msg.setData(response.getBody());
            }else {
                msg.setCode("500");
                msg.setData(response.getBody());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        logger.error("ZfbPaymentServiceimpl createOrderPayment is error",e);
        msg.setCode("500");
        }
        return msg;
    }

    @Override
    public ResponseMessage alipayNotiry(Map map) {
        logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-map:"+map);
        ResponseMessage responseMessage=new ResponseMessage();

        try {
            map.remove("sign_type");
            boolean signVerified= AlipaySignature.rsaCheckV2(map,appPublicId,"utf-8","RSA2");
            logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-signVerified："+signVerified);
            if (signVerified){
                //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                //支付宝订单号
                String tradeNo=new String(((String)map.get("trade_no")).getBytes("iso-8859-1"),"utf-8");
                //商户订单号
                String outTradeNo=new String(((String)map.get("out_trade_no")).getBytes("iso-8859-1"),"utf-8");
                //交易标题
                String title=new String(((String)map.get("subject")).getBytes("iso-8859-1"),"utf-8");
                //交易金额
                float price=Float.parseFloat((String)map.get("total_amount"));
                //截取手机号
                logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-title:"+title);
                String phoneNum=title.substring(title.lastIndexOf("-")+1);
                logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-phoneNum:"+phoneNum);
                Phone phone=new Phone();
                phone.setOrderNum(outTradeNo);
                phone.setPhoneNum(phoneNum);
                phone.setSurplus(price);
                logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-phone：传入数据库："+phone.toString());

                //交易状态
                String tradeStatus=new String(((String)map.get("trade_status")).getBytes("ISO-8859-1"),"utf-8");
                logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-tradeNo："+tradeNo+",outTradeNo:"+outTradeNo+",tradeStatus:"+tradeStatus);

                if (tradeStatus.equals("WAIT_BUYER_PAY")){
                    logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-tradeStatus：交易创建...");
                }else if (tradeStatus.equals("TRADE_SUCCESS")){
                    //数据库操作
                    logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-tradeStatus：支付成功...");
                    //存入手机充值信息到数据库
                    String success=phoneService.addPhone(phone);
                    logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-success:"+success);

                }else if(tradeStatus.equals("TRADE_FINISHED")){
                    logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-tradeStatus：交易完结...");
                }else if (tradeStatus.equals("TRADE_CLOSED")){
                    logger.debug("AlipayPaymentServiceImpl-alipayNotiry()-tradeStatus：交易关闭...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    生成随机数
     */
    @Override
    public String random() {
        String randomUid=UUID.randomUUID().toString();
        logger.debug("AlipayPaymentServiceImpl-random()-randomUid:"+randomUid);
        return randomUid;
    }
}
